<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">

    </style>
</head>

<body>
    <script type="text/javascript">
        var data = [{
                name: '老大1',
                id: 1,
                oldId: 0
            },
            {
                name: '老大2',
                id: 2,
                oldId: 0
            },
            {
                name: '老二1-1',
                id: 3,
                oldId: 1
            },
            {
                name: '老二1-2',
                id: 4,
                oldId: 1
            },
            {
                name: '老二2-1',
                id: 5,
                oldId: 2
            },
            {
                name: '老三1-2-1',
                id: 6,
                oldId: 4
            }

        ];

        function one(data, id) {
            let arr = [];
            data.forEach((item, index) => {
                if (item.oldId == id) {
                    let two = one(data, item.id)
                    if (two.length > 0) {
                        item.children = two
                    }
                    arr.push(item)
                }
            })
            return arr
        }
        console.log(one(data, 0));

        function one(data, id, pid) {
            let arr = [];
            data.forEach((item, index) => {
                if (item[pid] == id) {
                    let two = one(data, item.id, 'oldId')
                    if (two.length > 0) {
                        item.children = two
                    }
                    arr.push(item)
                }
            })
            return arr
        }
        console.log(one(data, 0, 'oldId'));
        [{
                name: "老大1",
                id: 1,
                oldId: 0,
                children: [{
                        name: "老二1-1",
                        id: 3,
                        oldId: 1
                    },
                    {
                        name: "老二1-2",
                        id: 4,
                        oldId: 1,
                        children: [{
                            name: "老三1-2-1",
                            id: 6,
                            oldId: 4
                        }]
                    },
                ]
            },
            {
                name: "老大2",
                id: 2,
                oldId: 0,
                children: [{
                    name: "老二2-1",
                    id: 5,
                    oldId: 2
                }]
            }
        ]
    </script>
</body>

</html>